'use strict';
var fayeClient = require('./faye-client');
var lodash = require('lodash');
var moment = require('moment');

module.exports = function(app, router) {
	router.get('/inventories/all', function*(req, res, next) {
		// console.log("/inventories/all", req.appApi);
		let result = yield req.appApi.get('/inventories?page=-1');
		var inventories = result.data.map(item => lodash.pick(item, ['name', 'id',
			'price', 'pic', 'categories', 'modifiers', 'unit', 'description',
			'combo', 'code', 'costPrice'
		]));
		let inventorySaleOuts = yield req.appApi.get('/inventories/soldOut');
		for (var i in inventories) {
			var findData = lodash.find(inventorySaleOuts.data, function(d) {
				return d.inventoryId == inventories[i].id;
			})
			if (findData) {
				inventories.splice(i, 1);
			}
		}
		let modifiers = (yield req.appApi.get('/modifiers/public')).data;
		for (var i in inventories) {
			let invt = inventories[i];
			let categories = invt.categories;
			var commonModifiers = lodash.filter(modifiers, modifier =>{
				//有交集
				if(modifier.applyCategories&&modifier.applyCategories.length==0){
					return true;
				}else{
					return 	lodash.intersectionBy(modifier.applyCategories, categories, category =>
					category.id).length > 0
				}
			});
			invt.modifiers = invt.modifiers.concat(commonModifiers);
		}
		inventories.map(item => lodash.remove(item.categories, function(cate) {
			return cate.parent;
		}));
		for (var i in inventories) {
			let invt = inventories[i];
			let categories = invt.categories;
			let modifiers = invt.modifiers;
			invt.categories = categories.map(item => lodash.pick(item, ['name', 'id']));
			invt.modifiers = modifiers.map(item => lodash.pick(item, ['name', 'id',
				'options', 'singleton', 'isRequired', 'isGeneral'
			]));
		}
		var nowTime = moment();
		var startTime = nowTime.startOf("month").format("YYYY-MM-DD");
		var endTime = nowTime.endOf("month").format("YYYY-MM-DD");

		var url = "/orders/salesOrders/inventories?from=" + startTime + "&to=" +
			endTime + "&page=-1&type=sales-out";
		let result1 = yield req.appApi.get(url);
		inventories.map(function(invt) {
			result1.data.map(function(inventory) {
				if (invt.id == inventory.id) {
					invt.qty = inventory.quantity;
				}
			})
		})
		res.send(inventories);
	});
}
